# -*- coding: utf-8 -*-
"""
菜单系统模块
实现三级菜单结构和导航
"""

import os
import sys
import time
from typing import Dict, List, Any, Optional
from .ui_components import UIComponents

# 调试信息
print(f"Loading menu_system.py from: {__file__}")


class MenuSystem:
    """菜单系统类"""
    
    def __init__(self, plugin_manager, config_manager):
        """初始化菜单系统"""
        self.plugin_manager = plugin_manager
        self.config_manager = config_manager
        self.ui = UIComponents()
        self.running = True
        self.current_path = []
        
        # 工具分类定义
        self.categories = {
            "文件工具": {
                "description": "文件处理相关工具",
                "plugins": ["httpserver", "text_tools"]
            },
            "网络工具": {
                "description": "网络相关工具",
                "plugins": ["httpserver"]
            },
            "系统工具": {
                "description": "系统信息和管理工具",
                "plugins": ["sysinfo", "app"]
            },
            "计算工具": {
                "description": "计算和数据处理工具",
                "plugins": ["calc"]
            }
        }
    
    def start(self):
        """启动菜单系统"""
        try:
            self.show_main_menu()
        except KeyboardInterrupt:
            self.safe_exit()
    
    def safe_exit(self):
        """安全退出"""
        self.ui.clear_screen()
        print("\n感谢使用多功能工具箱！再见！👋")
        self.running = False
    
    def show_main_menu(self):
        """显示主菜单"""
        while self.running:
            self.ui.clear_screen()
            self.current_path = ["主菜单"]
            self.ui.show_breadcrumb(self.current_path)
            
            # 显示标题
            self.ui.show_ascii_title("多功能工具箱")
            
            # 构建菜单内容
            menu_content = []
            for i, (category, info) in enumerate(self.categories.items(), 1):
                menu_content.append(f"[{i}] {category}")
            
            menu_content.append("")
            menu_content.append("0. 退出")
            
            # 显示菜单框
            menu_lines = self.ui.draw_box(menu_content, 40)
            for line in menu_lines:
                print(line)
            
            # 获取用户选择
            choice = self.ui.get_user_choice("请选择功能分类", allow_back=False)
            
            if choice == "0":
                self.safe_exit()
                break
            elif choice.isdigit():
                category_index = int(choice) - 1
                if 0 <= category_index < len(self.categories):
                    category_name = list(self.categories.keys())[category_index]
                    self.show_category_menu(category_name)
            else:
                self.ui.show_error_with_guide(
                    "无效的选择",
                    "请输入对应的数字编号"
                )
                self.ui.wait_for_enter()
    
    def show_category_menu(self, category_name: str):
        """显示分类菜单"""
        while self.running:
            self.ui.clear_screen()
            self.current_path = ["主菜单", category_name]
            self.ui.show_breadcrumb(self.current_path)
            
            category_info = self.categories[category_name]
            
            # 显示分类标题
            print(f"\n📁 {category_name}")
            print(f"   {category_info['description']}\n")
            
            # 获取该分类下的可用插件
            available_plugins = []
            all_plugins = self.plugin_manager.get_loaded_plugins()
            
            for plugin_name in category_info["plugins"]:
                if plugin_name in all_plugins:
                    plugin = all_plugins[plugin_name]
                    available_plugins.append((plugin_name, plugin))
            
            if not available_plugins:
                self.ui.show_error_with_guide(
                    "该分类下没有可用的工具",
                    "请检查插件是否正确加载"
                )
                self.ui.wait_for_enter()
                return
            
            # 构建工具菜单
            menu_content = []
            for i, (plugin_name, plugin) in enumerate(available_plugins, 1):
                menu_content.append(f"[{i}] {plugin.description}")
            
            menu_content.append("")
            menu_content.append("0. 退出 | B. 返回上级")
            
            # 显示菜单框
            menu_lines = self.ui.draw_box(menu_content, 50)
            for line in menu_lines:
                print(line)
            
            # 获取用户选择
            choice = self.ui.get_user_choice("请选择工具")
            
            if choice == "0":
                self.safe_exit()
                break
            elif choice.upper() == "B":
                break
            elif choice.isdigit():
                tool_index = int(choice) - 1
                if 0 <= tool_index < len(available_plugins):
                    plugin_name, plugin = available_plugins[tool_index]
                    self.show_tool_interface(plugin_name, plugin, category_name)
            else:
                self.ui.show_error_with_guide(
                    "无效的选择",
                    "请输入对应的数字编号，或输入 'B' 返回上级"
                )
                self.ui.wait_for_enter()
    
    def show_tool_interface(self, plugin_name: str, plugin, category_name: str):
        """显示工具界面"""
        while self.running:
            self.ui.clear_screen()
            self.current_path = ["主菜单", category_name, plugin.description]
            self.ui.show_breadcrumb(self.current_path)
            
            # 显示工具信息
            print(f"\n🔧 {plugin.description}")
            print(f"   版本: {plugin.version}\n")
            
            # 显示工具帮助
            help_info = plugin.get_help()
            print("📖 使用说明:")
            print(f"   {help_info}\n")
            
            # 工具操作菜单
            menu_content = [
                "[1] 启动工具",
                "[2] 查看帮助",
                "",
                "0. 退出 | B. 返回上级"
            ]
            
            menu_lines = self.ui.draw_box(menu_content, 40)
            for line in menu_lines:
                print(line)
            
            choice = self.ui.get_user_choice("请选择操作")
            
            if choice == "0":
                self.safe_exit()
                break
            elif choice.upper() == "B":
                break
            elif choice == "1":
                self.execute_tool(plugin_name, plugin)
            elif choice == "2":
                self.show_tool_help(plugin)
            else:
                self.ui.show_error_with_guide(
                    "无效的选择",
                    "请输入对应的数字编号，或输入 'B' 返回上级"
                )
                self.ui.wait_for_enter()
    
    def execute_tool(self, plugin_name: str, plugin):
        """执行工具"""
        self.ui.clear_screen()
        print(f"🚀 正在启动 {plugin.description}...\n")
        self.ui.show_loading("初始化工具")
        
        try:
            # 进入工具的交互模式
            self.run_tool_interactive(plugin_name, plugin)
        except KeyboardInterrupt:
            print("\n\n⚠️  工具执行被用户中断")
        except Exception as e:
            self.ui.show_error_with_guide(
                f"工具执行出错: {str(e)}",
                "请检查输入参数或联系开发者"
            )
        
        self.ui.wait_for_enter("工具执行完成，按回车返回")
    
    def run_tool_interactive(self, plugin_name: str, plugin):
        """运行工具的交互模式"""
        print(f"📝 {plugin.description} - 交互模式")
        print("   输入 'help' 查看帮助，输入 'exit' 或 'quit' 退出\n")
        
        while True:
            try:
                user_input = input(f"{plugin_name}> ").strip()
                
                if not user_input:
                    continue
                
                if user_input.lower() in ['exit', 'quit', 'q']:
                    break
                
                # 解析命令参数
                args = user_input.split()
                
                # 执行插件
                result = plugin.execute(args)
                
                if not result:
                    break
                    
            except KeyboardInterrupt:
                print("\n使用 'exit' 命令退出工具")
            except EOFError:
                break
    
    def show_tool_help(self, plugin):
        """显示工具帮助"""
        self.ui.clear_screen()
        print(f"📚 {plugin.description} - 详细帮助\n")
        
        help_info = plugin.get_help()
        print(help_info)
        print()
        
        # 如果插件有show_help方法，也调用它
        if hasattr(plugin, 'show_help'):
            plugin.show_help()
        
        self.ui.wait_for_enter()
    
    def _build_main_menu(self):
        """兼容旧版本的主菜单构建方法"""
        # 统一获取插件列表（兼容旧/新接口）
        try:
            plugins = self.plugin_manager.get_loaded_plugins()
        except AttributeError:
            plugins = self.plugin_manager.get_plugins()
        
        # 构造一个简单的主菜单结构用于兼容旧逻辑
        menu = {
            "categories": list(self.categories.keys()),
            "plugins": {name: getattr(plugin, 'description', name) for name, plugin in plugins.items()}
        }
        return menu